#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <strings.h>


void read_childproc(int sig){
    int status;
    pid_t ret = waitpid(-1,&status,WNOHANG);
    if (WIFEXITED(status)){
        printf("child [%d] return [%d]\n",ret,WEXITSTATUS(status));
    }
    
}

int main(int argc,char *argv[]){

    // 参数
    if(argc < 2){
        fprintf(stderr,"Usage argc ... \n");
        exit(-1);
    }  

    // 注册信号
    struct sigaction act;
    act.sa_handler = read_childproc;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    sigaction(SIGCHLD,&act,0);

    // 监听文件描述符
    int lfd = socket(PF_INET,SOCK_STREAM,0);
    if(lfd < 0){
        fprintf(stderr,"socket error\n");
        exit(-1);
    }  

    // 绑定端口号
    struct sockaddr_in ser_addr;
    bzero(&ser_addr,sizeof(ser_addr));
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_port = htons(atoi(argv[1]));
    ser_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    if(bind(lfd,(struct sockaddr *)&ser_addr,sizeof(ser_addr)) < 0){
        fprintf(stderr,"bind error\n");
        exit(-1);
    }

    // 监听
    if(listen(lfd,5) < 0){
        fprintf(stderr,"bind error\n");
        exit(-1);
    }  

    struct sockaddr_in cli_addr;
    socklen_t cli_len = sizeof(cli_addr);
    bzero(&cli_addr,cli_len);
    char buf[1024];
    int n;
    int cfd;

    while (1){
        cfd = accept(lfd,(struct sockaddr *)&cli_addr,&cli_len);
        if (cfd < 0){
            fprintf(stderr,"accept error\n");
            exit(-1);
        }

        pid_t pid = fork();
        if(pid < 0){
            close(cfd);
            fprintf(stderr,"fork error\n");
            exit(-1);
        }  

        if(pid == 0){
            close(lfd); // 这只是关闭子进程的lfd，并没有关闭父进程的lfd
            while ((n = read(cfd,buf,sizeof(buf))) != 0){
                write(cfd,buf,n);
            }
            close(cfd);
            return 0; // 这个很重要
        }else{
            close(cfd);
        }
    }
    

    close(lfd);
    return 0;
}